package com.lgy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lgy.dao.RepertoryDao;
import com.lgy.dao.SaleDao;
import com.lgy.pojo.Sale;
import com.lgy.service.IRepertoryService;
import com.lgy.service.ISaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class SaleServiceImpl implements ISaleService {
    @Autowired
    private SaleDao saleDao;


    @Override
    public PageInfo<Sale> findSaleList(Integer companyId,Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Sale> saleList =  saleDao.findAllSaleList(companyId);
        PageInfo<Sale> pageInfo = new PageInfo<>(saleList);
        return pageInfo;
    }

    @Override
    public int payment(Integer saleId) {
        return saleDao.updateBySaleId(saleId);
    }

    @Override
    public int insert(Sale sale) {
        Boolean flag = this.subRepertory( sale.getCompanyId(), sale.getCarId(),sale.getSaleNum());
        if(flag){
            sale.setSaleTotalPrice((sale.getSaleCurPrice().multiply(new BigDecimal(sale.getSaleNum()))));
            sale.setSaleTime(new Date());
            return saleDao.insert(sale);
        }
        return 0;
    }

    public Boolean subRepertory(Integer companyId,Integer carId,Integer carNum){

        Integer num = saleDao.findRepertoryNum(companyId,carId);
        if(num>=carNum){
            int i = saleDao.updateRepertoryNum(carId, companyId, carNum);
            return i>0;
        }
        return false;
    }

}
